﻿using System;
using System.Collections.Generic;
using Microsoft.Office.Interop.Outlook;
using Microsoft.TeamFoundation.Client;
using Microsoft.TeamFoundation.WorkItemTracking.Client;
using Outlook.WorkItems.Extension.Controls;
using Outlook.WorkItems.Extension.Manager.TeamProjectManager;

namespace Outlook.WorkItems.Extension.Addin.Actions
{
    public class ViewRelatedWorkItemAction : IBowieAction
    {
        private readonly ItemProperties _itemProperties;

        public ViewRelatedWorkItemAction(ItemProperties itemProperties)
        {
            _itemProperties = itemProperties;
        }

        public void Do()
        {
            WorkItemStore store = null;

            var teamServer = _itemProperties["TeamServer"];

            if (teamServer != null && !string.IsNullOrEmpty(teamServer.Value.ToString()))
            {
                var tfs = TfsTeamProjectCollectionFactory.GetTeamProjectCollection(new Uri(teamServer.Value.ToString()));
                store = tfs.GetService<WorkItemStore>();
            }
            else
            {
                var folder = _itemProperties.Parent.Parent as MAPIFolder;
                if (folder != null && TeamProjectLinksManager.ContainsTeamProjectLink(folder.EntryID))
                {
                    var link = TeamProjectLinksManager.GetTeamProjectLink(folder.EntryID);
                    var tfs = TfsTeamProjectCollectionFactory.GetTeamProjectCollection(new Uri(link.TeamServerUri));
                    store = tfs.GetService<WorkItemStore>();
                }
            }

            if (store == null)
                return;

            var relatedWorkItemsId = _itemProperties["RelatedWIIds"];
            if (relatedWorkItemsId == null || relatedWorkItemsId.Value == null) 
                return;

            var workItems = new List<WorkItem>();
            var wiIds = relatedWorkItemsId.Value.ToString();
            var splittedIds = wiIds.Split(';');
            foreach (var wiId in splittedIds)
            {
                int id;
                if (Int32.TryParse(wiId, out id))
                {
                    workItems.Add(store.GetWorkItem(id));
                }
            }

            using (var frm = new RelatedWorkItemsForm(workItems))
            {
                frm.ShowDialog();
            }
        }
    }
}
